<template>
  <div class="location" :class="[color == 'white' ? 'white' : 'black']" @click="getLocationCityHandle">
    <img :src="icon == 'white' ? whiteIcon : blackIcon" alt="" />
    <span>{{ $store.state.city }}</span>
  </div>
</template>

<script>
import cmblapi from 'cmblapi'
import { setCity } from '@/utils/session.js'
import { CITYDATA } from '@/utils/constConfig.js'
export default {
  name: 'Location',
  props: {
    color: {
      type: String,
      default: 'white',
    },
    icon: {
      type: String,
      default: 'white',
    },
  },
  data() {
    return {
      whiteIcon: require('../assets/img/location_icon_w.png'),
      blackIcon: require('../assets/img/location_icon_b.png'),
    }
  },
  methods: {
    getLocationCityHandle() {
      let _that = this
      cmblapi.requestUserPermission({
        apiName: 'getLocation',
        success: function() {
          cmblapi.getLocation({
            mapType: 'gd',
            success: (res) => {
              let { addressInfo } = res
              let city = addressInfo.city
              if (CITYDATA.includes(city)) {
                let [startTxt, endTxt] = city.split('市')
                setCity(startTxt)
              } else {
                setCity(city)
              }
              // 获取定位
              _that.$store.commit('changeCity', city)
            },
            fail: (err) => {},
          })
        },
        fail: function(res) {},
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.location {
  display: flex;
  align-items: center;
  font-size: 0.4rem;
  &.black {
    color: #333;
  }
  &.white {
    color: #fff;
  }
  img {
    margin-right: 0.133333rem;
    width: 0.24rem;
    height: 0.346667rem;
  }
}
</style>
